<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use app\model\{Order, UserBalanceFlow, MerchantFundFlow, CouponOrder, MerchantRechargeRecord, MerchantWithdrawRecord, RechargeAmount, PlatformConfig};
use app\service\{WechatService, AlipayService};
use think\facade\{Db, Log};
use think\Request;

class FinanceController extends BaseController
{
    /**
     * 获取财务概览数据
     */
    public function overview(Request $request)
    {
        try {
            $merchant_id = $request->merchant_id;
            $start_date = $request->get('start_date', date('Y-m-d'));
            $end_date = $request->get('end_date', date('Y-m-d'));
            
            // 快递订单统计
            $express_stats = Order::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'count(*) as order_count',
                    'sum(fee_actual) as total_fee',
                    'sum(merchant_profit) as total_profit'
                ])
                ->find();
            
            // 领券订单统计    
            $coupon_stats = CouponOrder::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'count(*) as order_count',
                    'sum(order_amount) as total_amount',
                    'sum(merchant_commission) as total_commission'
                ])
                ->find();
                
            // 资金流水统计
            $fund_stats = MerchantFundFlow::where([
                    ['merchant_id', '=', $merchant_id],
                    ['create_time', 'between time', [$start_date, $end_date]]
                ])
                ->field([
                    'fund_flow_type',
                    'sum(fund_flow_amount) as total_amount'
                ])
                ->group('fund_flow_type')
                ->select();
            
            $data = [
                'express' => [
                    'order_count' => $express_stats['order_count'] ?? 0,
                    'total_fee' => $express_stats['total_fee'] ?? 0,
                    'total_profit' => $express_stats['total_profit'] ?? 0
                ],
                'coupon' => [
                    'order_count' => $coupon_stats['order_count'] ?? 0,
                    'total_amount' => $coupon_stats['total_amount'] ?? 0,
                    'total_commission' => $coupon_stats['total_commission'] ?? 0
                ],
                'fund_flow' => $this->formatFundStats($fund_stats)
            ];
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $data]);
        } catch (\Exception $e) {
            Log::error('获取财务概览失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取资金流水记录
     */
    public function fundFlowList(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 流水类型筛选
            if (isset($params['fund_flow_type'])) {
                $where[] = ['fund_flow_type', '=', $params['fund_flow_type']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = MerchantFundFlow::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取资金流水记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 格式化资金流水统计数据
     */
    protected function formatFundStats($stats)
    {
        $result = [
            'recharge' => 0, // 充值
            'withdraw' => 0, // 提现
            'order_pay' => 0, // 订单支付
            'order_refund' => 0, // 订单退款
            'commission' => 0 // 分佣
        ];
        
        foreach ($stats as $item) {
            switch ($item['fund_flow_type']) {
                case 1:
                    $result['recharge'] = $item['total_amount'];
                    break;
                case 2:
                    $result['withdraw'] = $item['total_amount'];
                    break;
                case 3:
                    $result['order_pay'] = $item['total_amount'];
                    break;
                case 4:
                    $result['order_refund'] = $item['total_amount'];
                    break;
                case 5:
                    $result['commission'] = $item['total_amount'];
                    break;
            }
        }
        
        return $result;
    }

    /**
     * 获取充值金额配置
     */
    public function rechargeAmounts()
    {
        try {
            $list = RechargeAmount::order('sort', 'asc')->select();
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取充值金额配置失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 创建充值订单
     */
    public function createRecharge(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证金额
            if (empty($params['amount']) || $params['amount'] <= 0) {
                return json(['code' => 1, 'msg' => '充值金额必须大于0']);
            }
            
            // 生成订单号
            $order_no = 'CR' . date('YmdHis') . mt_rand(1000, 9999);
            
            // 创建充值记录
            $record = MerchantRechargeRecord::create([
                'merchant_id' => $merchant_id,
                'order_no' => $order_no,
                'recharge_amount' => $params['amount'],
                'recharge_type' => $params['recharge_type'],
                'status' => 0, // 未支付
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 根据支付方式返回支付参数
            $pay_data = [];
            switch ($params['recharge_type']) {
                case 1: // 微信支付
                    $wechatService = new WechatService($merchant_id);
                    $pay_data = $wechatService->createRechargeOrder($record);
                    break;
                    
                case 2: // 支付宝支付
                    $alipayService = new AlipayService($merchant_id);
                    $pay_data = $alipayService->createRechargeOrder($record);
                    break;
                    
                case 3: // 对公转账
                    $pay_data = $this->getTransferInfo();
                    break;
                    
                default:
                    throw new \Exception('不支持的支付方式');
            }
            
            Db::commit();
            return json([
                'code' => 0,
                'msg' => '创建成功',
                'data' => [
                    'order_no' => $order_no,
                    'amount' => $params['amount'],
                    'pay_params' => $pay_data
                ]
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('创建充值订单失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取充值记录
     */
    public function rechargeRecords(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 充值方式筛选
            if (isset($params['recharge_type'])) {
                $where[] = ['recharge_type', '=', $params['recharge_type']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = MerchantRechargeRecord::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取充值记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取对公转账信息
     */
    protected function getTransferInfo()
    {
        $config = PlatformConfig::where('group_name', 'transfer')
            ->column('config_value', 'config_key');
            
        return [
            'bank_name' => $config['bank_name'] ?? '',
            'bank_branch' => $config['bank_branch'] ?? '',
            'account_name' => $config['account_name'] ?? '',
            'account_no' => $config['account_no'] ?? '',
            'transfer_tips' => $config['transfer_tips'] ?? ''
        ];
    }

    /**
     * 提交对公转账凭证
     */
    public function submitTransfer(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            $record = MerchantRechargeRecord::where([
                'order_no' => $params['order_no'],
                'merchant_id' => $merchant_id,
                'recharge_type' => 3, // 对公转账
                'status' => 0 // 未支付
            ])->find();
            
            if (!$record) {
                return json(['code' => 1, 'msg' => '充值订单不存在或状态错误']);
            }
            
            $record->save([
                'transfer_no' => $params['transfer_no'],
                'status' => 1, // 已支付,待审核
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '提交成功,请等待审核']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('提交转账凭证失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 申请提现
     */
    public function withdraw(Request $request)
    {
        Db::startTrans();
        try {
            $params = $request->post();
            $merchant_id = $request->merchant_id;
            
            // 验证金额
            if (empty($params['amount']) || $params['amount'] <= 0) {
                return json(['code' => 1, 'msg' => '提现金额必须大于0']);
            }
            
            // 验证余额
            $merchant = Merchant::find($merchant_id);
            if ($merchant->balance < $params['amount']) {
                return json(['code' => 1, 'msg' => '余额不足']);
            }
            
            // 生成提现单号
            $withdraw_no = 'WD' . date('YmdHis') . mt_rand(1000, 9999);
            
            // 创建提现记录
            MerchantWithdrawRecord::create([
                'merchant_id' => $merchant_id,
                'withdraw_no' => $withdraw_no,
                'withdraw_amount' => $params['amount'],
                'withdraw_fee' => 0, // 手续费,可从配置读取
                'withdraw_name' => $params['withdraw_name'],
                'withdraw_account' => $params['withdraw_account'],
                'withdraw_account_type' => $params['withdraw_account_type'],
                'status' => 0, // 待审核
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 冻结余额
            $merchant->save([
                'balance' => Db::raw('balance-' . $params['amount']),
                'frozen_balance' => Db::raw('frozen_balance+' . $params['amount'])
            ]);
            
            // 记录资金流水
            MerchantFundFlow::create([
                'merchant_id' => $merchant_id,
                'fund_flow_type' => 2, // 提现
                'fund_flow_amount' => -$params['amount'],
                'order_no' => $withdraw_no,
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            Db::commit();
            return json(['code' => 0, 'msg' => '申请成功,请等待审核']);
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('申请提现失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 获取提现记录
     */
    public function withdrawRecords(Request $request)
    {
        try {
            $params = $request->get();
            $merchant_id = $request->merchant_id;
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            
            $where = [['merchant_id', '=', $merchant_id]];
            
            // 状态筛选
            if (isset($params['status'])) {
                $where[] = ['status', '=', $params['status']];
            }
            
            // 时间范围筛选
            if (!empty($params['start_time'])) {
                $where[] = ['create_time', '>=', $params['start_time']];
            }
            if (!empty($params['end_time'])) {
                $where[] = ['create_time', '<=', $params['end_time']];
            }
            
            $list = MerchantWithdrawRecord::where($where)
                ->order('id', 'desc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);
            
            return json(['code' => 0, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            Log::error('获取提现记录失败: ' . $e->getMessage());
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
} 